<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

// 引入模型
use App\Models\Business\Address as AddressModel;
use App\Models\Business\Business as BusinessModel;
use App\Models\Region as RegionModel;
// 引入Validator 门面
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class Address extends Controller
{
    // 添加地址
    public function add()
    {
        $params = request()->all();
        $busid = $params['busid'] ?? 0;
        $code = $params['code'] ?? 0;
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $parentpath = RegionModel::where('code', $code)->value('parentpath');

        if (!$parentpath) {
            return error('地区不存在');
        }
        $data = [
            'address' => $params['address'],
            'busid' => $busid,
            'consignee' => $params['consignee'],
            'mobile' => $params['mobile'],
            'status' => $params['status'],
        ];
        $path = explode(',', $parentpath);
        $data['province'] = $path[0] ?? '';
        $data['city'] = $path[1] ?? '';
        $data['district'] = $path[2] ?? '';
        // 验证规则
        $rule = [
            'mobile' => ['required', 'regex:/^1[3456789]{1}\d{9}$/'],
            'address' => ['required'],
            'busid' => ['required'],
            'consignee' => ['required'],
            'province' => ['required'],
            'city' => ['required'],
            'district' => ['required'],

        ];
        // 错误提示信息
        $message = [
            'mobile.required' => '手机号必填',
            'mobile.regex' => '手机号格式错误',
            'address.required' => '详情地址必填',
            'busid.required' => '用户id必填',
            'consignee.required' => '收货人姓名必填',
            'province.required' => '省必填',
            'city.required' => '市必填',
            'district.required' => '区必填',
        ];
        // 校验器
        $validator = Validator::make($data, $rule, $message);
        if ($validator->fails()) {
            // 检索特定字段的第一个错误信息 您可以使用 first 方法检索给定字段的第一个错误信息：
            return error($validator->errors()->first());
        }
        $addressinfo = AddressModel::where('busid', $busid)->where('status', '1')->first();
        DB::beginTransaction();
        try {
            if ($params['status'] == 1 && $addressinfo) {
                // 首先得找到当前用户下所有的收货地址ID
                $ids = AddressModel::where('busid', $busid)->pluck('id');
                // 批量更新当前拿到的ID的收货地址设置为非默认的
                AddressModel::whereIn('id', $ids)->update(['status' => '0']);
            }
            AddressModel::create($data);
            DB::commit();
            return success('添加成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('添加失败');
        }
    }
    // 编辑地址
    public function edit()
    {
        $params = request()->all();
        $res = AddressModel::find($params['id']);
        if (!$res) {
            return error('收货地址不存在');
        }
        $busid = $params['busid'] ?? 0;
        $code = $params['code'] ?? 0;
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $parentpath = RegionModel::where('code', $code)->value('parentpath');

        if (!$parentpath) {
            return error('地区不存在');
        }
        $data = [
            'address' => $params['address'],
            'busid' => $busid,
            'consignee' => $params['consignee'],
            'mobile' => $params['mobile'],
            'status' => $params['status'],
        ];
        $path = explode(',', $parentpath);
        $data['province'] = $path[0] ?? '';
        $data['city'] = $path[1] ?? '';
        $data['district'] = $path[2] ?? '';


        $addressinfo = AddressModel::where('busid', $busid)->where('status', '1')->first();
        DB::beginTransaction();
        try {
            if ($params['status'] == 1 && $addressinfo) {
                // 首先得找到当前用户下所有的收货地址ID
                $ids = AddressModel::where('busid', $busid)->pluck('id');
                // 批量更新当前拿到的ID的收货地址设置为非默认的
                AddressModel::whereIn('id', $ids)->update(['status' => '0']);
            }
            if ($params['status'] == 0 && !$addressinfo) {
                $data['status'] = 1;
            }
            AddressModel::where('id', $params['id'])->update($data);
            DB::commit();
            return success('编辑成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('编辑失败');
        }
    }
    // 删除地址
    public function del()
    {
        $id = request('id', 0);
        $addressinfo = AddressModel::destroy($id);
        if (!$addressinfo) {
            return error('删除失败');
        }
        return success('删除成功');
    }
    // 设置默认地址
    public function setDefault()
    {
        $busid = request('busid', 0);
        $id = request('id', 0);
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $addressinfo = AddressModel::where('busid', $busid)->where('status', '1')->first();
        DB::beginTransaction();
        try {
            if ($addressinfo) {
                // 首先得找到当前用户下所有的收货地址ID
                $ids = AddressModel::where('busid', $busid)->pluck('id');
                // 批量更新当前拿到的ID的收货地址设置为非默认的
                AddressModel::whereIn('id', $ids)->update(['status' => '0']);
            }
            AddressModel::where('id', $id)->update(['status' => '1']);
            DB::commit();
            return success('设置默认地址成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('设置默认地址失败');
        }
    }
    // 获取地址列表
    public function getAddressList()
    {
        $busid = request('busid', 0);
        $businessinfo = BusinessModel::find($busid)->orderBy('id', 'desc');
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $info = AddressModel::Where('busid', $busid)->get()->toArray();
        if (!$info) {
            return error('暂无地址');
        }
        return success('获取成功', $info);
    }
    // 根据id查询地址
    public function getAddressById()
    {
        $id = request('id', 0);
        $info = AddressModel::find($id);
        if (!$info) {
            return error('暂无地址');
        }
        return success('获取成功', $info);
    }
    // 获取默认地址
    public function order()
    {
        $busid = request('busid', 0); 

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $data = AddressModel::where(['busid' => $busid, 'status' => '1'])->first();

        return success('', $data);
    }
}
